package com.company.cloud.mall.modules.mgr.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.common.auth.annotation.StaffLogc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.log.annotation.SysLog;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.mall.constant.MallErrorEnum;
import com.company.cloud.mall.modules.api.response.OrderModel;
import com.company.cloud.mall.modules.api.response.OrderRefundsModel;
import com.company.cloud.mall.modules.app.service.ShopAfterSaleRefundsService;
import com.company.cloud.mall.modules.app.service.ShopOrderService;
import com.company.cloud.mall.modules.base.entity.OrderLog;
import com.company.cloud.mall.modules.base.entity.OrderRefunds;
import com.company.cloud.mall.modules.base.service.OrderLogService;
import com.company.cloud.mall.modules.base.service.OrderRefundsService;
import com.company.cloud.mall.modules.mgr.controller.req.OrderRefundCheckParam;
import com.company.cloud.mall.modules.mgr.controller.req.OrderRefundMgrQuery4PageParam;
import com.company.cloud.mall.modules.utils.ShopOrderConvertUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.constant.IRelBusiType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/mgr/mall/orderRefund")
@Api(tags="Shop_Mgr_退款管理")
public class OrderRefundMgrController {

	@Autowired
	private OrderRefundsService orderRefundsService;
	@Autowired
	private UserRemoteService userRemoteService;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private ShopAfterSaleRefundsService shopAfterSaleRefundsService;
	@Autowired
	private ShopOrderService shopOrderService;

	
	@PostMapping("/query")
	@ApiOperation(value="退款单查询", response=BaseResult.class)
	public BaseResult query(@RequestBody OrderRefundMgrQuery4PageParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
			if(YNEnum.YES.getCode().equals(params.getIsAgent())) {
				params.setCompanyNo(userInfo.getCompanyNo());
			}else {
				params.setMainCompanyNo(userInfo.getCompanyNo());
				params.setIsAgent(null);
			}

	    IPage<OrderRefunds> page =  orderRefundsService.page(
	    		new Page<>(params.getPage(), params.getRows()),
			  new QueryWrapper<OrderRefunds>()
			  .eq(StringUtils.hasText(params.getMainCompanyNo()), "main_company_no", params.getMainCompanyNo())
			  .eq(StringUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
			  .apply(StringUtils.hasText(params.getIsAgent()), "main_company_no <> company_no")
			  .like(StringUtils.hasText(params.getSn()), "sn", params.getSn())
			  .eq(StringUtils.hasText(params.getState()), "state", params.getState())
			  .eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
			  .orderByDesc("cdt")
				);

	    if(page==null && CollectionUtils.isEmpty(page.getRecords())) {
	    	return BaseResult.ok();
	    }
	    
	    Set<Integer> userids=new HashSet<Integer>();
	    page.getRecords().forEach(item->{userids.add(item.getUserId());});
	    //todo
	    BaseClientResult<Map<Integer, UserSimple>> userResp=userRemoteService.getUserMapByIds(userids);
	    Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userResp);
		 IPage<OrderRefundsModel> data = page.convert(new Function<OrderRefunds, OrderRefundsModel>() {
			@Override
			public OrderRefundsModel apply(OrderRefunds entity) {
				return ShopOrderConvertUtils.getOrderRefunds(entity,userMap);
			}
		 });
		
		return BaseResult.ok(data);
	}
	
	
	@GetMapping("/get")
	@ApiOperation(value="订单退款明细",response = OrderRefundsModel.class)
	public BaseResult get(@RequestParam("sn")String sn) {
		OrderRefunds entity=orderRefundsService.getById(sn);
		if(entity==null) {
			throw new BusinessException(MallErrorEnum.Order_After_Refunds_NotExist);
		}
		List<OrderLog> records=orderLogService.list(new QueryWrapper<OrderLog>()
				.eq("order_type", IRelBusiType.Order_Refunds_ObjType).eq("sn", sn).orderByAsc("cdt"));
		
		 Set<Integer> userIds=new HashSet<Integer>();
		 userIds.add(entity.getUserId());
		 if(!CollectionUtils.isEmpty(records)) {
			 records.forEach(item->{ userIds.add(item.getCman()); });
		 }
		 //todo
		 BaseClientResult<Map<Integer, UserSimple>> userResp=userRemoteService.getUserMapByIds(userIds);
		 Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userResp);
		 
		 OrderRefundsModel data=ShopOrderConvertUtils.getOrderRefunds(entity,records,userMap);
		 
		 OrderModel orderInfo=shopOrderService.getOrder(entity.getOrderSn(), entity.getOrderItemId(), false, true, false, false, false);
		 data.setOrderInfo(orderInfo);
		 return BaseResult.ok(data);
	}
	
	
	@PostMapping("/check")
	@SysLog("订单退款审核")
	@ApiOperation(value="订单退款审核")
	@StaffLogc(title = "订单退款审核", action = "订单退款审核", actionAdo = "订单退款")
	public BaseResult check(@RequestBody OrderRefundCheckParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		shopAfterSaleRefundsService.check(params, userInfo);
		return BaseResult.ok();
	}
	
	@GetMapping("/refund")
	@SysLog("退款订单退款")
	@ApiOperation(value="退款订单退款")
	@StaffLogc(title = "退款订单退款", action = "退款订单退款", actionAdo = "订单退款")
	public BaseResult refund(@RequestParam("sn")String sn) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		shopAfterSaleRefundsService.refund(sn, userInfo);
		return BaseResult.ok();
	}
	
	
	
	
}
